pub mod event;
use std::sync::RwLock;

use event::Event;
use mf_core::event::EventBus;
use state::TypeMap;
static APPLICATION_CONTEXT: TypeMap![Send + Sync] = <TypeMap![Send + Sync]>::new();
/// 全局工具类
pub struct ContextHelper;

impl ContextHelper {
    /// 获取事件总线
    pub fn get_event_bus() -> &'static RwLock<EventBus<Event>> {
        // 如果event_bus不存在，则创建一个
        let event_bus = APPLICATION_CONTEXT.try_get::<RwLock<EventBus<Event>>>();
        if event_bus.is_none() {
            let event_bus: EventBus<Event> = EventBus::new();
            APPLICATION_CONTEXT.set(RwLock::new(event_bus));
        }
        APPLICATION_CONTEXT.get::<RwLock<EventBus<Event>>>()
    }

    /// 设置全局变量
    pub fn set<T: Send + Sync + 'static>(v: T) {
        APPLICATION_CONTEXT.set(v);
    }
    /// 设置线程局部变量
    pub fn set_local<T, F>(
        &self,
        state_init: F,
    ) -> bool
    where
        T: Send + 'static,
        F: Fn() -> T + Send + Sync + 'static,
    {
        APPLICATION_CONTEXT.set_local(state_init)
    }
    /// 获取线程局部变量
    pub fn get_local<T: Send + 'static>(&self) -> &T {
        APPLICATION_CONTEXT.get_local::<T>()
    }
    /// 获取全局变量
    pub fn try_get<T: Send + Sync + 'static>() -> Option<&'static T> {
        APPLICATION_CONTEXT.try_get::<T>()
    }
    /// 获取全局变量
    pub fn get<T: Send + Sync + 'static>() -> &'static T {
        APPLICATION_CONTEXT.get::<T>()
    }
}
